#!/usr/bin/env python

"""
Build Script for Peerscape Firefox Extension (peerscape-3.x.xpi)
"""

from __future__ import with_statement

import os
import sys
import shutil
import subprocess

URL = 'http://peerscape.googlecode.com/svn/trunk/'

FILES = [
    'README',
    'install.rdf',
    'chrome.manifest',
    'chrome/content/fusion-16.png',
    'chrome/content/fusion-gray-16.png',
    'chrome/content/fusion-active-16.png',
    'chrome/content/fusion-32.png',
    'chrome/content/peerscapeOverlay.js',
    'chrome/content/peerscapeOverlay.xul',
    'chrome/content/peerscapeOverlay.css',
    'chrome/content/peerscapeLog.js',
    'chrome/content/peerscapeLog.xul',
    'chrome/locale/en/peerscape.dtd',
    'idl/pyIPeerscapeManager.idl',
    'components/peerscapeproxy.js',
    'components/pyIPeerscapeManager.xpt',
    'components/pyPeerscapeManager.py',
    'defaults/preferences/prefs.js',
    ]

TARGET = 'peerscape-%s.xpi'

def copy(src, dst):
    dir = os.path.dirname(dst)
    if not os.path.exists(dir):
        os.makedirs(dir)
    shutil.copy(src, dst)

def patch(filename, old, new):
    with open(filename) as f:
        s = f.read()
    with open(filename, 'w') as f:
        f.write(s.replace(old, new))

if os.path.exists('build'):
    sys.exit('Please remove old build directory first.')

os.umask(022)

for src in FILES:
    dst = os.path.join('build', src)
    copy(src, dst)

os.chdir('build')

subprocess.check_call(['svn', 'export', '--quiet', URL, 'pylib'])
shutil.rmtree('pylib/content')
shutil.rmtree('pylib/firefox')

# The addons.mozilla.org validator complains about these files:
os.remove('pylib/peerscape/i18n/extract.sh')
os.remove('pylib/peerscape/i18n/init.sh')
os.remove('pylib/peerscape/i18n/update.sh')

execfile('pylib/peerscape/version.py') # Get definition of VERSION.

patch('install.rdf', 'VERSION', VERSION)

target = TARGET % VERSION
zip_command = 'zip -q -r ../%s *' % target
subprocess.check_call(zip_command, shell=True)

os.chdir('..')
shutil.rmtree('build')
